/* eslint-disable prettier/prettier */
import React, {Component} from 'react';
import {
  StyleSheet,
  Platform,
  ToastAndroid,
  View,
  ActivityIndicator,
  Dimensions,
  BackHandler,
} from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
import CameraRoll from '@react-native-community/cameraroll';
import RNFS from 'react-native-fs';
import Icon from 'react-native-vector-icons/FontAwesome';
type Props = {};
const screenWidth = Dimensions.get('window').width;
const screenHeight = Dimensions.get('window').height;
export default class ImageView extends Component<Props> {
  constructor(props) {
    super(props);

    this.state = {
      isShow: false,
      index: 0,
      images: [],
      animating: true,
    };
  }
  renderLoad() {
    //loading
    return (
      <View style={{marginTop: screenHeight / 2}}>
        <ActivityIndicator animating={true} size={'large'} />
      </View>
    );
  }
  close() {
    this.setState({isShow: false});
  }

  savePhoto(uri) {
    if (!uri) {
      return null;
    }
    return new Promise((resolve, reject) => {
      let timestamp = new Date().getTime(); //获取当前时间错
      let random = String((Math.random() * 1000000) | 0); //六位随机数
      let dirs =
        Platform.OS === 'ios'
          ? RNFS.LibraryDirectoryPath
          : RNFS.ExternalDirectoryPath; //外部文件，共享目录的绝对路径（仅限android）
      const downloadDest = `${dirs}/${timestamp + random}.jpg`;
      const formUrl = uri;
      const options = {
        fromUrl: formUrl,
        toFile: downloadDest,
        background: true,
        begin: (res) => {
          console.log('begin', res);
          console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
        },
      };
      try {
        const ret = RNFS.downloadFile(options);
        ret.promise
          .then((res) => {
            var promise = CameraRoll.saveToCameraRoll(downloadDest);
            promise
              .then(function (result) {
                ToastAndroid.show('保存成功！', ToastAndroid.SHORT);
              })
              .catch(function (error) {
                // console.log('error', error);
                ToastAndroid.show('保存失败！\n' + error, ToastAndroid.SHORT);

              });
            resolve(res);
          })
          .catch((err) => {
            reject(new Error(err));
          });
      } catch (e) {
        reject(new Error(e));
      }
    });
  }
  // componentDidMount() {
  //   BackHandler.addEventListener(
  //     'hardwareBackPress',
  //     this.onBackButtonPressAndroid,
  //   );
  // }
  // componentWillUnmount() {
  //   BackHandler.removeEventListener(
  //     'hardwareBackPress',
  //     this.onBackButtonPressAndroid,
  //   );
  // }

  // onBackButtonPressAndroid = () => {
  //   this.props.navigation.goBack();
  // };
  render() {
    const {params} = this.props.route;
    return (
      <View style={styles.container}>
        <ImageViewer
          style={styles.container}
          imageUrls={params.arr}
          index={params.index}
          menuContext={{saveToLocal: '保存图片到相册', cancel: '取消'}}
          onSave={(url) => {
            this.savePhoto(url);
          } }
            onSwipeDown={() => {
              this.props.navigation.goBack();
            }}
          enableSwipeDown={true}
          enablePreload={true}
          loadingRender={this.renderLoad}
        />
        <View style={ styles.textStyle }>
        <Icon name={'angle-left'} size={30} color={'#fff'}  onPress={() => {
              this.props.navigation.goBack();
            }}/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: '#000',
  },
  textStyle: {
    paddingLeft: 10,
    paddingTop: 25,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    position: 'absolute',
    top: 10,
    left: 20,
    right: 20,
  },
  btnStyle: {
    marginTop: 10,
    paddingRight: 10,
    paddingTop: 25,
    justifyContent: 'flex-end',
    flexDirection: 'row',
  },
});
